// pages/upAppointmentInfo/upAppointmentInfo.js
const app = getApp()
Page({
  data: {
    primaryColor: app.primaryColor, // 主题色
    datePickerShow: false, // 选择日期时间的弹框
    currentDate: null, // picker 选择框赋值的
    selectedTime: '',  // 当前选择的时间
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      } else if (type === 'day') {
        return `${value}日`;
      } else if (type === 'hour') {
        return `${value}时`;
      } else if (type === 'minute') {
        return `${value}分`;
      }
      return value;
    }
  },
  onLoad(options) {

  },
  onShow() {
    this.initDateTime()
  },
  // 确定改变日期
  confirmDate(event) {
    const selectedDate = new Date(event.detail);
    this.setData({
      currentDate: event.detail,
      selectedTime: this.formatTime(selectedDate),
      datePickerShow: false
    })

  },
  // 关闭日期选择框
  cancelDate () {
    this.setData({ datePickerShow: false })
  },
  // 打开日期选择框
  chooseDate () {
    this.setData({
      datePickerShow: true
    })
  },
  // 初始化默认时间
  initDateTime() {
    let timestamp;

    if (this.data.selectedTime) {
      // 有默认值时，转换为时间戳
      timestamp = new Date(this.data.selectedTime).getTime();
    } else {
      // 无默认值时，使用当前时间戳
      timestamp = new Date().getTime();
    }

    // 更新数据
    this.setData({
      currentDate: timestamp,
      selectedTime: this.formatTime(new Date(timestamp))
    });
  },

  // 格式化时间为 "YYYY-MM-DD HH:MM"
  formatTime(date) {
    const year = date.getFullYear();
    const month = this.padZero(date.getMonth() + 1);
    const day = this.padZero(date.getDate());
    const hour = this.padZero(date.getHours());
    const minute = this.padZero(date.getMinutes());
    return `${year}/${month}/${day} ${hour}:${minute}`;
  },

  // 补零函数
  padZero(n) {
    return n < 10 ? `0${n}` : n;
  }
})